package leetcode.backtrace;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Lc40 {

    List<List<Integer>> ans ;
    boolean[] visited;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        visited = new boolean[candidates.length];
        ans = new ArrayList<>();
        backtack(candidates, target, new ArrayList<Integer>(), 0);
        return ans;
    }

    private void backtack(int[] candidates, int target, ArrayList<Integer> list, int start) {
        if (target == 0 && list.size() != 0) {
            ans.add(new ArrayList<>(list));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            if (target < candidates[i]) return;
            if (visited[i] || (i > 0 && candidates[i] == candidates[i-1] && !visited[i-1])) continue;
            visited[i] = true;
            list.add(candidates[i]);
            backtack(candidates, target - candidates[i], list, i);
            list.remove(list.size() - 1);
            visited[i] = false;
        }
    }

    public static void main(String[] args) {

        Lc40 lc40 = new Lc40();
        int[] candidates = {-1,-1,-1,1,1,1};
        int target = 0;
        System.out.println(lc40.combinationSum2(candidates, target));
    }
}
